//
//  HistoryViewController.m
//  MountEverestFM
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 chenn. All rights reserved.
//

#import "HistoryViewController.h"
#import "PlayerInforTableViewCell.h"
#import "CollectModel.h"
#import "Player.h"
#import "HistoryModel.h"

@interface HistoryViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIBarButtonItem *righBtn;
@property (nonatomic, strong) NSMutableArray *deleteArr;

@end

@implementation HistoryViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"历史记录";

    self.righBtn = [[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStyleBordered target:self action:@selector(rightBtnAction:)];
    self.navigationItem.rightBarButtonItem = _righBtn;

    self.deleteArr = [NSMutableArray array];
    
    DBHandler *db = [DBHandler shareInstance];
    [db openDB];
    NSArray *arr = [db selectAllCollect];
    self.dataArray = [NSMutableArray arrayWithArray:arr];
    [db closeDB];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.separatorStyle = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [self.tableView registerClass:[PlayerInforTableViewCell class] forCellReuseIdentifier:@"history"];
    if (_dataArray.count == 0) {
        UILabel *noneLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, FM_Screen_Height / 2, FM_Screen_Width, 40 * FM_Screen_Pts_Height)];
        noneLabel.text = @"暂无记录";
        noneLabel.textAlignment = NSTextAlignmentCenter ;
        [self.view addSubview:noneLabel];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    
    PlayerInforTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"history"];
    CollectModel *collect = [_dataArray objectAtIndex:indexPath.row];
    cell.albumLabel.text = collect.albumTitle;
    
    NSURL *url = [NSURL URLWithString:collect.AlbumCoverSmall];
    [cell.headView sd_setImageWithURL:url];
    cell.titleLabel.text = collect.title;
    
    CGFloat time = [collect.rePlayTime doubleValue];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"mm:ss";
    NSDate *totelDate = [NSDate dateWithTimeIntervalSince1970:time];
    NSString *dateStr = [formatter stringFromDate:totelDate];
    cell.timeLabel.text = [NSString stringWithFormat:@"上次播放至: %@", dateStr];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.righBtn.title isEqualToString:@"删除"]) {
        Player *player = [Player shareInstance];
        if (player.listArr.count != 0) {
            [player collectPreseve];
        }
        NSMutableArray *historyArr = [NSMutableArray array];
        for (CollectModel *collect in _dataArray) {
            HistoryModel *historyModel = [[HistoryModel alloc]init];
            historyModel.index = indexPath.row;
            historyModel.nickname = collect.nickname;
            historyModel.albumCoverSmall = collect.AlbumCoverSmall;
            historyModel.intro = collect.intro;
            historyModel.albumTitle = collect.albumTitle;
            
            historyModel.playUrl64 = collect.playUrl64;
            historyModel.title = collect.title;
            historyModel.coverSmall = collect.coverSmall;
            historyModel.coverLarge = collect.coverLarge;
            historyModel.rePlayTimes = collect.rePlayTime;
            [historyArr addObject:historyArr];
        }
        player.history = YES;
        player.number = indexPath.row;
        player.historyArr = historyArr;
        [player playFromNet];
    [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
    if ([self.righBtn.title isEqualToString:@"确定"]) {
        
        [self.deleteArr addObject:[_dataArray objectAtIndex:indexPath.row]];
        //        NSLog(@"Select---->:%@",self.selectedDic);
    }
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    //ViewControler 提供了一个可以切换状态的edit按钮
    [super setEditing:editing animated:animated];
    
    //开启编辑状态
    [self.tableView setEditing:!editing animated:animated];
    if (self.editing) {
        self.editButtonItem.title = @"完成";
    }
    else{
        self.editButtonItem.title = @"编辑";
    }
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


- (void)rightBtnAction:(UIBarButtonItem *)btn
{
    [self.tableView setEditing:YES animated:YES];
    _righBtn.title = @"确定";
    [_righBtn setAction:@selector(righBtnWithsure:)];
}

- (void)righBtnWithsure:(UIBarButtonItem *)btn
{
    
    NSLog(@"%@", _dataArray);
    [_dataArray removeObjectsInArray:_deleteArr];
    
    DBHandler *db = [DBHandler shareInstance];
    [db openDB];
    for (CollectModel *collected in _deleteArr) {
        NSLog(@"%@", collected);
        [db deleteVideo:collected];
    }
    [db closeDB];
    [_deleteArr removeAllObjects];
    [self.tableView reloadData];
    
    _righBtn.title = @"删除";
    [_righBtn setAction:@selector(rightBtnAction:)];
    [self.tableView setEditing:NO animated:YES];
    
    if (_dataArray == nil) {
        UILabel *noneLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, FM_Screen_Width, 40 * FM_Screen_Pts_Height)];
        noneLabel.text = @"暂无记录";
        [self.view addSubview:noneLabel];
    }
}


//取消一项
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.righBtn.title isEqualToString:@"确定"]) {
        [_deleteArr removeObject:[_dataArray objectAtIndex:indexPath.row]];
        //        NSLog(@"Deselect---->:%@",self.selectedDic);
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
   
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
